package com.kdyzm.typora.upload.plugin.utils;

import cn.hutool.core.date.DateTime;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kdyzm.typora.upload.plugin.model.TokenHeader;
import com.kdyzm.typora.upload.plugin.properties.ConfigProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.HttpCookie;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author kdyzm
 */
@Component
@Slf4j
public class TokenUtils {

    @Autowired
    private ConfigProperties configProperties;

    @Autowired
    private ObjectMapper objectMapper;

    private static final String JSESSIONID = "JSESSIONID";

    public TokenHeader getToken() {
        HttpResponse response = HttpRequest.get(configProperties.getHomePage()).execute();
        Map<String, Object> req = new HashMap<>();
        req.put("username", configProperties.getUserName());
        req.put("password", configProperties.getPassword());
        HttpCookie jsessionid = response.getCookie(JSESSIONID);
        HttpRequest.post(configProperties.getLoginUrl()).form(req).cookie(jsessionid).execute();
        return new TokenHeader().setKey(JSESSIONID).setValue(jsessionid.getValue());
    }

}
